<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class wms_ctl_admin_recalcexpressfee extends desktop_controller{
    
    var $workground = 'wms_ctl_admin_recalcexpressfee';
    var $pagelimit = 10;
    public function __construct($app)
    {
        parent::__construct($app);
        header("cache-control: no-store, no-cache, must-revalidate");
    }

    function index()
    {

        //add by 判断当前登录用是否是超级管理员，以及拥有的门店
        $is_super = kernel::single('desktop_user')->is_super();
        if (!$is_super) {
            $info = app::get('desktop')->model('users')->dump(kernel::single('desktop_user')->get_id(), 'shopIds');
            if (empty($info['shopIds'])) {
                header('Content-Type:text/html; charset=utf-8');
                echo app::get('desktop')->_("您没有对应店铺权限");exit;
            }
            $shopIds = explode(",", $info['shopIds']);

            $shop = app::get('ome')->model('shop')->getList('shop_id, name,AXCustomer', array('shop_id'=>$shopIds));
            unset($shopIds);
            foreach ($shop as $key => $value) 
            {
                $shop_ids[]="'".$value['shop_id']."'";
                if(empty($value['AXCustomer']))
                {
                    $shopIds[]= array('shop_id' => $value['shop_id'],'shop_name'=>'【无】'.$value['name']);   
                }else{
                    $shopIds[]= array('shop_id' => $value['shop_id'],'shop_name'=>'【'.$value['AXCustomer'].'】'.$value['name']);   
                }
            }
        } else {
            $shop = app::get('ome')->model('shop')->getList('shop_id, name,AXCustomer');
            foreach ($shop as $key => $value) 
            {
                $shop_ids[]="'".$value['shop_id']."'";
                if(empty($value['AXCustomer']))
                {
                    $shopIds[]= array('shop_id' => $value['shop_id'],'shop_name'=>'【无】'.$value['name']);   
                }else{
                    $shopIds[]= array('shop_id' => $value['shop_id'],'shop_name'=>'【'.$value['AXCustomer'].'】'.$value['name']);   
                }
            }
        }
        $this->pagedata['shopIds'] = $shopIds;

        //客户
        $sqlcustomer="select distinct AXCustomer,customername from sdb_ome_shop where AXCustomer!=''";
        $customer_data = kernel::database()->select($sqlcustomer);
        foreach ($customer_data as $key => $value) 
        {
            $customers[]= array('AXCustomer' => $value['AXCustomer'],'customername'=>'【'.$value['AXCustomer'].'】'.$value['customername']);   
        }
        $this->pagedata['customers'] = $customers;

        //仓库
        $branchObj = app::get('ome')->model('branch');
        $branch_rows = $branchObj->getList('branch_id,name',array('owner'=>'1', 'b_type'=>1),0,-1);

        foreach($branch_rows as $branch)
        {
            $branch_list []  = array('branch_id' => $branch['branch_id'],'name'=>$branch['name'] );
            $branch_ids[]=$branch['branch_id'];
        }
        $this->pagedata['branch_list'] = $branch_list;

        //快递公司
         $sql="select corp_id,name as logi_name from sdb_ome_dly_corp";
        $loginameList = kernel::database()->select($sql);
        $this->pagedata['loginameList'] = $loginameList;
        //时间
        $begin = strtotime($_POST['begin_date']);
        $end = strtotime($_POST['end_date']);
        $_POST['begin_date'] = $_POST['begin_date'] . ' ' . $_POST['_DTIME_']['H']['begin_date'] . ':' . $_POST['_DTIME_']['M']['begin_date'];
        
        $begin = strtotime($_POST['begin_date']);
        $query_begin=$begin;
        $_POST['end_date'] = $_POST['end_date'] . ' ' . $_POST['_DTIME_']['H']['end_date'] . ':' . $_POST['_DTIME_']['M']['end_date'];
        $end = strtotime($_POST['end_date']);
        $query_end=$end;
        $_POST['begin_date'] = $_POST['begin_date'] ? $_POST['begin_date'] : $begin_date;
        $_POST['end_date'] = $_POST['end_date'] ? $_POST['end_date'] : $end_date;

        if ($_POST['begin_date']) {
            $_POST['begin_date'] = strtotime($_POST['begin_date']);
            $_POST['begin_date'] = date("Y-m-d H:i:s", $_POST['begin_date']);
        }
        if ($_POST['end_date']) {
            $_POST['end_date'] = strtotime($_POST['end_date']);
            $_POST['end_date'] = date("Y-m-d H:i:s", $_POST['end_date']);
        }

        $clearingtable['shop'] = $_POST['shop'];
        $clearingtable['logi_name'] = $_POST['logi_name'];
        $clearingtable['branchname'] = $_POST['branchname'];
        $clearingtable['bn'] = $_POST['bn'];
        $clearingtable['arzero'] = $_POST['arzero'];
        $clearingtable['apzero'] = $_POST['apzero'];
        $clearingtable['arcalc'] = $_POST['arcalc'];
        $clearingtable['apcalc'] = $_POST['apcalc'];
        $clearingtable['isshiparea'] = $_POST['isshiparea'];
        $clearingtable['AXCustomer'] = $_POST['AXCustomer'];
        $clearingtable['AXCustomer_code'] = $_POST['AXCustomer_code'];


        #统计日期
        if ($_POST['begin_date'] == '1970-01-01 08:00:00' || !$_POST['begin_date']) {

            $begin_date = strtotime(date("Y-m-d H:i:s", time()));
            $clearingtable['begin_date'] = $begin_date;
        } else {
            $begin_date = $_POST['begin_date'];
            $clearingtable['begin_date'] = $begin;
        }
        if ($_POST['end_date'] == '1970-01-01 08:00:00' || !$_POST['begin_date']) {
            $end_date = strtotime(date("Y-m-d H:i:s", time()));
            $clearingtable['end_date'] = $end_date;
        } else {
            $end_date = $_POST['end_date'];
            $clearingtable['end_date'] = $end;
        }
        //查询核算数量
        $sql="SELECT w.area_id, region.region_id,w.ship_area,w.logi_id,w.shop_id,w.net_weight,w.delivery_id as wms_delivery_id,w.delivery_time,a.deliverycomp_time,o.delivery_bn,o.delivery_id,odo.order_id,w.ship_city
            FROM sdb_wms_deliverycomp a 
            inner join sdb_wms_deliverycomp_line b on a.id = b.deliverycomp_id
            inner join sdb_wms_deliverynote_line d on b.deliverynote_id = d.deliverynote_id
            inner join sdb_wms_delivery w on d.delivery_bn = w.delivery_bn
            left join sdb_ome_delivery as o on w.outer_delivery_bn=o.delivery_bn 
            inner JOIN sdb_ome_delivery_order odo on odo.delivery_id =o .delivery_id 
            inner join sdb_wms_delivery_items items on items.delivery_id=w.delivery_id 
            inner join sdb_ome_shop s on w.shop_id=s.shop_id 
left join sdb_eccommon_regions region on SUBSTRING_INDEX(substring_index(w.ship_area, ':', -2),':',-1)=region.region_id 
            WHERE w.type='normal' AND  w.status='3' AND  w.disabled='false' AND w.deliverytype != 'pickup' and w.delivery_id not in(SELECT delivery_id from sdb_wms_expressadjust_line)";
        if(!empty($_POST['shop']))
        {
            $sql.=" and w.shop_id='".$_POST['shop']."'";
        }else
        {
            $sql.=" and w.shop_id in(".implode(",",$shop_ids).")";
        }
        if(!empty($_POST['logi_name']))
        {
            $sql.=" and w.logi_id='".$_POST['logi_name']."'";
        }
        if(!empty($_POST['branchname']))
        {
            $sql.=" and w.branch_id='".$_POST['branchname']."'";
        }else
        {
            $sql.=" and w.branch_id in(".implode(",", $branch_ids).")";
        }
        if(!empty($query_begin) && !empty($query_end))
        {
            $sql.=" and a.deliverycomp_time>=".$query_begin." and a.deliverycomp_time<".$query_end;
        }

        if(!empty($_POST['bn']))
        {
            $sql.=" and items.bn='".$_POST['bn']."'";
        }
        if(!empty($_POST['arzero']))
        {
            $sql.=" and w.lmfee=0 ";
        }
        if(!empty($_POST['apzero']))
        {
            $sql.=" and w.delivery_cost_actual=0 ";
        }
        if(!empty($_POST['isshiparea']))
        {
            $sql.=" and region.region_id is null ";
        }
        if(empty($_POST['arcalc']) || empty($_POST['apcalc']))
        {
            if(!empty($_POST['arcalc']))
            {
                $sql.="  and s.JSType ='0'  ";
            }
            if(!empty($_POST['apcalc']))
            {
                $sql.=" and (s.JSType ='1' or s.JSType ='2')";
            }

        }
        
        if(!empty($_POST['AXCustomer']))
        {
            $sql.=" and s.AXCustomer='".$_POST['AXCustomer']."'";
        }
        if(!empty($_POST['AXCustomer_code']))
        {
            $sql.=" and s.AXCustomer='".$_POST['AXCustomer_code']."'";
        }
error_log($sql,3,'/data/www/oms/data/recal.log');        
        if(!empty($_POST['query']))
        {
            $delivery_data = kernel::database()->select($sql);
            if(!empty($delivery_data))
            {   
                if(!empty($_POST['iscalc']))
                {
                    $db = kernel::database();
                    $deliveryObj = app::get('wms')->model('delivery');
                    $deliveryMdj = app::get('ome')->model('delivery');
                    $omefeeLib    = kernel::single('ome_expressfee');
                    $orderSplitLib    = kernel::single('ome_order_split');
                    foreach ($delivery_data as $key => $value) 
                    {
                        //校验是否结账期间内，否则不允许重算；

                        list($area_prefix,$area_chs,$area_id) = explode(':',$value['ship_area']);
                        list($privince,$city,$country) = explode('/',$area_chs);
                        $weight   = $orderSplitLib->getDeliveryWeight($value['order_id'],array(),$value['delivery_id']);
                        if(empty($value['region_id']))
                        {
                            //1. 先查区域，找到后直接返回
                            //2. 再查市区，找到后直接返回
                            //3. 最后查省，找到后直接返回
                            $calc_area_id=$this->getareaid($country,3);
                            if(empty($calc_area_id))
                            {
                                $calc_area_id=$this->getareaid($city,2);
                                if(empty($calc_area_id))
                                {
                                    $calc_area_id=$this->getareaid($privince,1);
                                    if(!empty($calc_area_id))
                                    {
                                        $inparams['area_id']=$calc_area_id[0]['region_id'];   
                                    }
                                }else
                                {
                                    $inparams['area_id']=$calc_area_id[0]['region_id'];   
                                }
                            }else
                            {
                                $inparams['area_id']=$calc_area_id[0]['region_id'];   
                            }
                        }else{
                            $inparams['area_id']=$this->validateareaid($area_id,$city,$privince); 
                        }
                        $inparams['logi_id']=$value['logi_id'];
                        $inparams['shop_id']=$value['shop_id'];
                        $inparams['weight']=$weight;
                        $inparams['delivery_time']=$value['delivery_time'];
                        $inparams['ship_city']=$value['ship_city'];
                        $ship_area=$area_prefix.":".$area_chs.":".$inparams['area_id'];
                       
                        if($_POST['arcalc']=='on' && empty($_POST['apcalc']))
                        {
                            $data['lmfee']=$omefeeLib->AutoCalcExpressfee($inparams);
                            if($data['lmfee']==0)
                            {
                                $failcount+=1;
                            }
                            $db->exec("update sdb_ome_delivery set lmfee=".$data['lmfee'].",area_id=".$inparams['area_id'].",ship_area='".$ship_area."',net_weight=$weight,weight=$weight,last_modified=".time()." where delivery_id=".$value['delivery_id']) ;
                            $db->exec("update sdb_wms_delivery set lmfee=".$data['lmfee'].",area_id=".$inparams['area_id'].",ship_area='".$ship_area."',net_weight=$weight,weight=$weight,last_modified=".time()." where delivery_id=".$value['wms_delivery_id']);

                        }elseif(empty($_POST['arcalc']) && $_POST['apcalc']=='on')
                        {

                            $price = $deliveryMdj->getDeliveryFreightcity($inparams['ship_city'],$value['logi_id'],$weight);
                            if($price==0)
                            {
                                $failcount+=1;
                            }
                            $db->exec("update sdb_ome_delivery set area_id=".$inparams['area_id'].",ship_area='".$ship_area."',net_weight=$weight,weight=$weight,delivery_cost_actual=$price,delivery_cost_expect=$price,last_modified=".time()." where delivery_id=".$value['delivery_id']) ;
                            $db->exec("update sdb_wms_delivery set area_id=".$inparams['area_id'].",ship_area='".$ship_area."',net_weight=$weight,weight=$weight,delivery_cost_actual=$price,delivery_cost_expect=$price,last_modified=".time()." where delivery_id=".$value['wms_delivery_id']);
                            $db->exec("update sdb_wms_delivery_items set flatfeeprice=$price where delivery_id=".$value['wms_delivery_id']); 

                        }elseif($_POST['arcalc']=='on' && $_POST['apcalc']=='on')
                        {
                            $data['lmfee']=$omefeeLib->AutoCalcExpressfee($inparams);
                            error_log("数量【".$key."】".json_encode($inparams).'---'.$data['lmfee'], 3, PUBLIC_DIR . '/recalc' . date('Y-m-d') . '.log');
                            $price = $deliveryMdj->getDeliveryFreightcity($inparams['ship_city'],$value['logi_id'],$weight);
                            if($price==0)
                            {
                                $failcount+=1;
                            }
                            $db->exec("update sdb_ome_delivery set lmfee=".$data['lmfee'].",area_id=".$inparams['area_id'].",ship_area='".$ship_area."',net_weight=$weight,weight=$weight,delivery_cost_actual=$price,delivery_cost_expect=$price,last_modified=".time()." where delivery_id=".$value['delivery_id']) ;
                            $db->exec("update sdb_wms_delivery set lmfee=".$data['lmfee'].",area_id=".$inparams['area_id'].",ship_area='".$ship_area."',net_weight=$weight,weight=$weight,delivery_cost_actual=$price,delivery_cost_expect=$price,last_modified=".time()." where delivery_id=".$value['wms_delivery_id']);
                            $db->exec("update sdb_wms_delivery_items set flatfeeprice=$price where delivery_id=".$value['wms_delivery_id']);   
                        }
                    }
                }
            }
        }
        $this->pagedata['resultdata']['sumcount'] =count($delivery_data);

        if(!empty($_POST['iscalc']))
        {
            $this->pagedata['resultdata']['succcount'] =($this->pagedata['resultdata']['sumcount']-$failcount);
            $this->pagedata['resultdata']['failcount'] =$failcount;
        }
        $this->pagedata['clearingtable'] = $clearingtable;
        
        $this->page('admin/recalcexpressfee/reportshow.html');
        
    }
    //根据区域重新获取area
    function getareaid($area,$region_grade)
    {
        $sql="SELECT region_id from sdb_eccommon_regions where region_grade=$region_grade and local_name='$area'";
        return kernel::database()->select($sql);
    }
     //根据区域重新获取area
    function validateareaid($area,$city,$privince)
    {
        $sql="SELECT p_region_id from sdb_eccommon_regions where region_id=".$area;
        $data= kernel::database()->select($sql);
        if(!empty($data[0]['p_region_id']))
        {
            return $area; 

        }else{

            $sql1="SELECT region_id from sdb_eccommon_regions where region_grade=2 and local_name='$city'";
            $data1= kernel::database()->select($sql1);
            if(!empty($data1))
            {
                return $data1[0]['region_id'];
            }else{

                $sql2="SELECT region_id from sdb_eccommon_regions where region_grade=1 and local_name='$privince'";
                $data2= kernel::database()->select($sql2);
                if(!empty($data2))
                {
                    return $data2[0]['region_id'];
                }
            }
        }
    }
}
